/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011      Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
 
http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.javascript;

import java.util.HashMap;

import net.youmi.android.AdManager;
import net.youmi.android.spot.SpotDialogListener;
import net.youmi.android.spot.SpotManager;

import org.cocos2dx.CrazyBounce.R;
import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxGLSurfaceView;
import org.cocos2dx.lib.Cocos2dxJavascriptJavaBridge;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.listener.BmobUpdateListener;
import cn.bmob.v3.update.BmobUpdateAgent;
import cn.bmob.v3.update.UpdateResponse;
import cn.bmob.v3.update.UpdateStatus;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;


// The name of .so is specified in AndroidMenifest.xml. NativityActivity will load it automatically for you.
// You can use "System.loadLibrary()" to load other .so files.

public class AppActivity extends Cocos2dxActivity{

    static String hostIPAdress = "0.0.0.0";
    private static AppActivity app = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        
        if(nativeIsLandScape()) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
        }
        if(nativeIsDebug()){
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
        hostIPAdress = getHostIpAddress();
        
        app = this;
      //youmi ad initial.
      		AdManager.getInstance(this).init("a0518857a5aa5bc4", "d9bf5d10884dd341", false);
      		SpotManager.getInstance(this).loadSpotAds();
      		SpotManager.getInstance(this).setSpotOrientation(
      	            SpotManager.ORIENTATION_PORTRAIT);
      		SpotManager.getInstance(this).setAnimationType(SpotManager.ANIM_SIMPLE);
    }
    
    public static void autoUpdate() {

    	app.runOnUiThread(new Runnable() {
            @Override
            public void run() {
		        Bmob.initialize(app, "ed10df38d2981d775f2772a735ac2fca");
		
		        //only invoke once
//		        BmobUpdateAgent.initAppVersion(app);
		
		        BmobUpdateAgent.setUpdateOnlyWifi(false);
		        BmobUpdateAgent.update(app);
		
		        BmobUpdateAgent.setUpdateListener(new BmobUpdateListener() {
		
		            @Override
		            public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) {
		
		                //根据updateStatus来判断更新是否成功
		                if(updateStatus == UpdateStatus.No)
		                    Toast.makeText(app, "这是最新版本！", Toast.LENGTH_SHORT).show();
		            }
		        });
            }
      	 });

    }
    
    public static void invokeSun() {
    	app.runOnUiThread(new Runnable() {
            @Override
            public void run() {
           	 	Toast.makeText(app, "已获得20金币！！！", Toast.LENGTH_LONG).show();
           	 	
           		Uri uri = Uri.parse("http://www.cheerby.cn/activity/index.html?xxyixing");

           		Intent intent = new Intent(Intent.ACTION_VIEW,uri);

           		getContext().startActivity(intent);
            }
   	 });
    }
    
    public static void showAd(){
   	 app.runOnUiThread(new Runnable() {
            @Override
            public void run() {
           	 	Toast.makeText(app, "注意！点击广告即会开始下载广告展示的应用！点击右上角关闭广告！", Toast.LENGTH_LONG).show();
           	 	SpotManager.getInstance(app).showSpotAds(app);
            }
   	 });
   	
   }
	public static void showShare(final float time) {

       //杩欓噷涓�瀹氳浣跨敤runOnUiThread
       app.runOnUiThread(new Runnable() {
           @Override
           public void run() {
           	ShareSDK.initSDK(app);
           	 OnekeyShare oks = new OnekeyShare();
           	 //关闭sso授权
           	 oks.disableSSOWhenAuthorize(); 
           	 
           	// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
           	 //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
           	 // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
           	 oks.setTitle("快来玩" + app.getString(R.string.app_name) + "！");
           	 // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
           	 oks.setTitleUrl("http://www.1-xing.com/crazybounce.html");
           	 
           	 // text是分享文本，所有平台都需要这个字段
           	 oks.setText("我在嗨球里坚持了" + (int)(time) + "秒！" + getShareString((int) time));
           	 oks.setImageUrl("http://dashboard.mob.com/Uploads/40036f9939a5c6fd4313960fa91b5a1c.png");
           	 // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
           	 //oks.setImagePath("/data/data/org.cocos2dx.Tower/files/src/icon.png");//确保SDcard下面存在此张图片
           	 // url仅在微信（包括好友和朋友圈）中使用
           	 oks.setUrl("http://www.1-xing.com/crazybounce.html");
           	 // comment是我对这条分享的评论，仅在人人网和QQ空间使用
           	 oks.setComment("太好玩了！快来试试！");
           	 // site是分享此内容的网站名称，仅在QQ空间使用
           	 oks.setSite("益行");
           	 // siteUrl是分享此内容的网站地址，仅在QQ空间使用
           	 oks.setSiteUrl("http://www.1-xing.com/crazybounce.html");
           	 
           	 oks.setCallback(new PlatformActionListener() {
				
				@Override
				public void onError(Platform arg0, int arg1, Throwable arg2) {
					Log.d("crazy", "error");
					Message message = new Message();
					message.what = ERROR;
					handler.sendMessage(message);
				}
				
				@Override
				public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
					Log.d("crazy", "complete");
					Message message = new Message();
					message.what = COMPLETE;
					handler.sendMessage(message);
				}
				
				@Override
				public void onCancel(Platform arg0, int arg1) {
					
					Message message = new Message();
					message.what = CANCEL;
					handler.sendMessage(message);
					Log.d("crazy", "cancel");
				}
			});
           	// 启动分享GUI
           	 oks.show(app);
           	 
           }
       });
   }
	
	private static String getShareString(int tempTime) {
		
		String resultString = "超越了";
		String percentString;
      	 if(tempTime < 11) {//
      		 percentString = "0%";
      	 } else if (tempTime < 13) {// 10%
      		percentString = "10%";
      	 } else if(tempTime == 13) { // 20%
      		percentString = "20%";
      	 } else if(tempTime == 14) { // 28%
      		percentString = "28%";
      	 } else if(tempTime == 15) { // 35%
      		percentString = "35%";
      	 } else if(tempTime < 18) { //41%
      		percentString = "41%";
      	 } else if(tempTime == 18) { // 47%
      		percentString = "47%";
      	 } else if(tempTime < 21) { // 50%
      		percentString = "50%";
		} else if(tempTime < 23) { // 55%
			percentString = "55%";
		} else if(tempTime < 25) { // 62%
			percentString = "62%";
		} else if(tempTime < 29) { // 67%
			percentString = "67%";
		} else if(tempTime == 29) { // 71%
			percentString = "71%";
		} else if(tempTime < 33) { //77%
			percentString = "77%";
		} else if(tempTime < 42) { // 82%
			percentString = "82%";
		} else if(tempTime < 49) { // 88%
			percentString = "88%";
		} else if(tempTime < 55) { // 90%
			percentString = "90%";
		} else if(tempTime < 92) { // 95%
			percentString = "95%";
		} else if(tempTime < 100) { // 98%
			percentString = "98%";
		} else { // 99%
			percentString = "99%";
		}
      	 
      	 String nameString = "";
      	 if(tempTime >= 200) { //扫地阿姨
      		 nameString = "扫地阿姨";
      	 } else if(tempTime >= 180) {//设计神
      		nameString = "设计神";
      	 } else if(tempTime >= 160) {//攻城狮
      		nameString = "攻城狮";
      	 } else if(tempTime >= 140) {//产品狗
      		nameString = "产品狗";
      	 } else if(tempTime >= 120) {//CEO
      		nameString = "CEO";
      	 } else if(tempTime >= 100) {//无敌球王
      		nameString = "无敌球王";
      	 } else if(tempTime >= 80) {//超级球王
      		nameString = "超级球王";
      	 } else if(tempTime >= 60) {//球球保护者
      		nameString = "球球保护者";
      	 } else if(tempTime >= 40) {//球球爱慕者
      		nameString = "球球爱慕者";
      	 }
      	 
      	 if(tempTime >= 40)
      		 return resultString + percentString + "的手残星人，获得了" + nameString + "称号，快一起来挑战吧！";
      	 else
      		return resultString + percentString + "的手残星人，快一起来挑战吧！";
	}
	
	public final static int COMPLETE = 0, CANCEL = 1, ERROR = 2;
	public static Handler handler = new Handler() {
		
		public void handleMessage(Message message) {
			
			switch(message.what) {
			case COMPLETE:
				Toast.makeText(app, "分享成功！已获得20金币！", Toast.LENGTH_LONG).show();
				app.runOnGLThread(new Runnable() {
		            @Override
		            public void run() {
		                Cocos2dxJavascriptJavaBridge.evalString(
		                		"shareSuccess()");
		            }
		        });
				break;
			case CANCEL:

				Toast.makeText(app, "新浪微博分享成功可获得金币哦！！！", Toast.LENGTH_LONG).show();
				break;
			case ERROR:
				Toast.makeText(app, "分享出错", Toast.LENGTH_LONG).show();
				break;
			}
		}
	};
	
    @Override
    public Cocos2dxGLSurfaceView onCreateView() {
        Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
        // TestCpp should create stencil buffer
        glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);

        return glSurfaceView;
    }

    public String getHostIpAddress() {
        WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
        int ip = wifiInfo.getIpAddress();
        return ((ip & 0xFF) + "." + ((ip >>>= 8) & 0xFF) + "." + ((ip >>>= 8) & 0xFF) + "." + ((ip >>>= 8) & 0xFF));
    }
    
    public static String getLocalIpAddress() {
        return hostIPAdress;
    }
    
    private static native boolean nativeIsLandScape();
    private static native boolean nativeIsDebug();
    
}
